package com.example.blogdevelop.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blogdevelop.common.lang.Result;
import com.example.blogdevelop.entity.Blog;
import com.example.blogdevelop.entity.Form;
import com.example.blogdevelop.entity.Tag;
import com.example.blogdevelop.mapper.BlogMapper;
import com.example.blogdevelop.mapper.TagMapper;
import com.example.blogdevelop.service.BlogService;
import com.example.blogdevelop.service.TagService;
import com.example.blogdevelop.service.UserService;
import com.example.blogdevelop.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;

    @Autowired
    TagService tagService;

    @Autowired
    UserService userService;

    @Autowired
    BlogMapper blogMapper;

    @Autowired
    TagMapper tagMapper;
    //获取博客列表



    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") int currentPage, int pageSize) {

        Page page = new Page(currentPage, pageSize);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        List<Blog> list = pageData.getRecords();
        List<Form> formList = new ArrayList<>();
        for (Blog b: list) {
            Form form = new Form();
            BeanUtil.copyProperties(b, form);
            formList.add(form);
            form.setStatus(b.getStatus());
            form.setUserName(userService.getById(form.getUserId()).getUsername());
            form.setTags(tagMapper.selectByBlogId(form.getId()));
        }
        page.setRecords(formList);
        pageData.setTotal(page.getTotal());
        return Result.success(pageData);
    }
    //获取单一博客
    @GetMapping("/index/{id}")
    public Result detail(@PathVariable(name = "id") Integer id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已被删除");
        Form form = new Form();
        BeanUtil.copyProperties(blog, form);
        form.setUserName(userService.getById(form.getUserId()).getUsername());
        form.setTags(tagMapper.selectByBlogId(id));
        return Result.success(form);
    }


    @RequiresAuthentication
    @PostMapping("/add")
    public Result edit(@Validated @RequestBody Form form) {

//        Assert.isTrue(false, "公开版不能任意编辑！");

        Blog blog = new Blog();
        BeanUtil.copyProperties(form, blog);

        log.info("userId={}" ,ShiroUtils.getProfile().getUsername());
        blog.setUserId(ShiroUtils.getProfile().getId());
        blog.setCreated(LocalDateTime.now());
        if(blog.getStatus() == null) {
            blog.setStatus(0);
        }
        blogService.save(blog);
        List<Tag> tags = form.getTags();
        for (Tag tag : tags) {
            tag.setBlogId(blog.getId());
            tagService.save(tag);
        }

        return Result.success(detail(blog.getId()));
//        Blog temp ;
//
//
//
//        if(blog.getId() != null) {
//            //文章id已经存在？
//            temp = blogService.getById(blog.getId());
//            // 只能编辑自己的文章
//            System.out.println(ShiroUtils.getProfile().getId());
//            Assert.isTrue(temp.getUserId().intValue() == ShiroUtils.getProfile().getId().intValue(), "没有权限编辑");
//
//        } else {
//
//            temp = new Blog();
//            temp.setUserId(ShiroUtils.getProfile().getId());
//            temp.setCreated(LocalDateTime.now());
//            temp.setStatus(blog.getStatus());
//        }
//
//        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
//        blogService.saveOrUpdate(temp);
//        return Result.success(null);
    }

    @RequiresAuthentication
    @PostMapping("/edit/{blogId}")
    public Result update(@PathVariable(name = "blogId") int blogId, @Validated @RequestBody Blog edited) {
        Blog blog = blogService.getById(blogId);
        if (edited.getId() != null) {
            Assert.isTrue(blogId == edited.getId(), "没有权限编辑");
        }
        edited.setCreated(LocalDateTime.now());
        edited.setUserId(ShiroUtils.getProfile().getId());
        edited.setStatus(blog.getStatus());
        edited.setId(blogId);
        BeanUtil.copyProperties(edited,blog , "id", "userId", "status");
        blogService.updateById(edited);

        return Result.success(detail(blogId));
    }


    @RequiresAuthentication
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable(name = "id") int id){
        Blog blog = blogService.getById(id);

        blogService.deleteMain(id);
        return Result.success(null);
    }

    @GetMapping("/search")
    public Result search(@Validated @RequestBody List<Tag> tags ) {
        List<Blog> blogs = blogMapper.getAllBlog();
        List<Form> forms = new ArrayList<>();
        for (Blog blog : blogs) {
            List<Tag> currentTag = tagMapper.selectByBlogId(blog.getId());
            Form form = new Form();
            BeanUtil.copyProperties(blog, form);
            form.setUserName(userService.getById(blog.getUserId()).getUsername());
            form.setTags(currentTag);
            Boolean flag = false;
            for(Tag blogTag : currentTag){
                for(Tag postTag : tags){
                    if(blogTag.getTagKind().equals(postTag.getTagKind())){
                        forms.add(form);
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    break;
                }
            }
        }
        return Result.success(forms);
    }

}